package com.vcc.web.core.queue.batch.close.queue;

import com.vcc.service.service.TaskLogService;
import com.vcc.service.service.UserCardService;
import com.vcc.web.core.component.PingPongComponent;
import com.vcc.web.core.queue.batch.close.model.CloseQueueDto;
import com.vcc.web.core.queue.pingpong.queue.OpenCardQueue;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.DelayQueue;
import java.util.concurrent.Executors;

@Component
public class CloseQueue implements CommandLineRunner {

    @Autowired
    private UserCardService userCardService;
    @Autowired
    private PingPongComponent pingPongComponent;
    @Autowired
    private TaskLogService taskLogService;

    private static final Logger logger = LoggerFactory.getLogger(OpenCardQueue.class);

    private volatile DelayQueue<CloseQueueDto> delayQueue = new DelayQueue<CloseQueueDto>();


    public void add(String orderId, String cardNumber, Integer index, Integer targetIndex) {
        synchronized (this) {
            CloseQueueDto closeQueueDto = delayQueue.stream().filter(it -> it.getCardNumber().equals(cardNumber) && it.getOrderId().equals(orderId)).findFirst().orElse(null);
            if (closeQueueDto == null) {
                LocalDateTime now = LocalDateTime.now();
                LocalDateTime nowB = now.plusSeconds(5L);
                long betweenMillis = ChronoUnit.MILLIS.between(now, nowB);
                logger.info("当前添加的是${orderId},秒${time}");
                delayQueue.put(
                        new CloseQueueDto(
                                System.currentTimeMillis() + betweenMillis, cardNumber, orderId, index, targetIndex
                        )
                );
            }
        }
    }


    @Override
    public void run(String... args) throws Exception {
        Executors.newSingleThreadExecutor().execute(new Thread(this::excuteThread));
    }

    private void excuteThread() {
        while (true) {
            try {
                processTask(delayQueue.take());
            } catch (InterruptedException e) {
                break;
            }
        }
    }

    /**
     * 内部执行延时任务
     * //INACTIVE 待激活
     *         //ACTIVE 正常
     *         //REVOKED 已冻结
     *         //INCANCELED 注销中
     *         //CANCELED 已注销
     * @param task
     */
    private void processTask(CloseQueueDto task) {
//        try {
//            logger.info("当前处理的卡是{}", task.getCardNumber());
//            UserCard userCard = userCardService.getByCardNumber(task.getCardNumber());
//            CardData cardData = pingPongComponent.queryCardBalance(userCard.getChannelCardId());
//            if (Objects.equals(new BigDecimal(cardData.getAvailableBalance()).compareTo(BigDecimal.valueOf(0)),0)) {
//                pingPongComponent.close(userCard);
//                taskLogService.processedSuccess(task.getOrderId());
//            }else {
//                taskLogService.processedError(task.getOrderId());
//            }
//        } catch (Exception e) {
//            taskLogService.processedError(task.getOrderId());
//            logger.error("异常", e);
//        } finally {
//            if (task.getIndex().equals(task.getTargetIndex())) {
//                taskLogService.processedAccomplish(task.getOrderId());
//            }
//        }
    }
}
